package aleksandar.djuric.common;

import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class TimeManagement {
	private static TimeManagement tm;

	private Calendar nextTrainingDate;
	
	private Format justDate, timeAndDate, lastOnlineFormater;
	
	public TimeManagement()
	{
		justDate = new SimpleDateFormat("dd/MM/yyyy");
		timeAndDate = new SimpleDateFormat("hh:mm dd/MM/yyyy.");
		lastOnlineFormater = new SimpleDateFormat("[''dd/MM/yyyy HH:mm z'']");
	}
	
	public static TimeManagement getTM()
	{
		if(tm == null)
			tm = new TimeManagement();
		return tm;
	}

	public String getNextTrainingDate()
	{
		if(nextTrainingDate != null)
			return justDate.format(nextTrainingDate.getTime());
		else 
			return null;
	}
	
	public String getNextTrainingTime()
	{
		if(nextTrainingDate != null)
		{
			return timeAndDate.format(nextTrainingDate.getTime());
		}
		else
			return "";
	}
	
	public void setNextTrainingDate(String date)
	{
		try {
			nextTrainingDate = new GregorianCalendar(
					TimeZone.getTimeZone("UTC"));
			nextTrainingDate.setTime((Date)justDate.parseObject(date));
			nextTrainingDate.set(Calendar.HOUR_OF_DAY, 24);
		} catch (ParseException e) {
			nextTrainingDate = null;
//			e.printStackTrace();
		}
	}
	
	public String getTime() {
		Calendar curDate = new GregorianCalendar(
				TimeZone.getTimeZone("UTC"));
		curDate.set(Calendar.HOUR_OF_DAY, 24);
		curDate.set(Calendar.MINUTE, 0);
		curDate.set(Calendar.SECOND, 0);
		return justDate.format(curDate.getTime());
	}
	
	public boolean canTrain()
	{
		if(nextTrainingDate != null)
		{
			if(Calendar.getInstance().compareTo(nextTrainingDate) > 0)
				return true;
			else
				return false;
		}
		else
			return true;
	}
	
	public Date getDate(String s) {
		try {
			return (Date)lastOnlineFormater.parseObject(s);
		} catch (ParseException e) {
//			e.printStackTrace();
			return new Date(0);
		}
	}
	
	public String getString(Date d)
	{
		try{
			return lastOnlineFormater.format(d);
		} catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		TimeManagement tzc = new TimeManagement();
		tzc.setNextTrainingDate(tzc.getTime());
		System.out.println(tzc.getNextTrainingDate());
		System.out.println(tzc.nextTrainingDate.getTime());
		System.out.println(Calendar.getInstance().getTime());
		System.out.println(tzc.canTrain());
	}
	

}
